#include "account.h"
#include "pluginbase.h"
#include "taskmanager.h"
#include "globalconfig.h"
#include "maindlg.h"

#include <QSettings>
#include <QStringList>
#include <QNetworkReply>
#include <QNetworkAccessManager>
#include <QNetworkCookie>
#include <QNetworkCookieJar>
#include <QTimer>


Account::Account(QObject* parent) :
        QObject(parent)
{
    login = false;
    netReady = true;
    net = new QNetworkAccessManager();
    connect(net, SIGNAL(finished(QNetworkReply*)), this, SLOT(netFinished()));
}

void Account::updateCookies()
{
    //save cookies
    QList<QNetworkCookie> ckList = net->cookieJar()->cookiesForUrl(QUrl("http://www.kaixin001.com"));
    QString cookies;
    QList<QNetworkCookie>::Iterator it = ckList.begin();
    while(it != ckList.end())
    {
        QNetworkCookie ck = *it;
        cookies += ck.toRawForm() + ", ";
        ++it;
    }
    this->cookies = cookies;
}


void Account::netFinished()
{
    this->netReady = true;
    QTimer::singleShot(gConf.interval, this, SLOT(doTask()));
}
void Account::doTask()
{
    TaskManager::self()->doTask(this);
}



















AccountManager* AccountManager::me = NULL;
bool AccountManager::load()
{
    if(!settings)
        return false;
    actMap.clear();
    QStringList groupList = settings->childGroups();
    QStringList::Iterator git = groupList.begin();
    while(git != groupList.end())
    {
        QString groupName = *git;
        if(groupName.startsWith("Account"))
        {
            int uid;
            bool ok;
            if((uid = groupName.mid(7).toInt(&ok)) && !ok)
            {
                ++git;
                continue;
            }
            if(actMap.contains(uid))
            {
                ++git;
                continue;
            }
            Account* act = new Account();
            act->uid = uid;
            settings->beginGroup(groupName);
            act->name = settings->value("Name", "").toString();
            act->user = settings->value("User", "").toString();
            act->pwd = settings->value("Password", "").toString();
            act->active = settings->value("Active", false).toBool();
            act->loginKey = settings->value("LoginKey", "").toString();
            act->cookies = settings->value("Cookies", "").toString();
            PluginManager::self()->load(act);
            settings->endGroup();
            actMap[uid] = act;
        }
        ++git;
    }
    return true;
}

bool AccountManager::save()
{
    if(!settings)
        return false;
    QMap<uint, Account*>::Iterator it = actMap.begin();
    while(it != actMap.end())
    {
        Account* act = *it;
        if(act->uid <= 0)
            continue;
        act->updateCookies();
        QString gName = "Account" + QString::number(act->uid);
        settings->beginGroup(gName);
        settings->setValue("Name", act->name);
        settings->setValue("User", act->user);
        settings->setValue("password", act->pwd);
        if(!act->cookies.isEmpty())
            settings->setValue("Cookies", act->cookies);
        settings->setValue("Active", act->active);
        settings->setValue("LoginKey", act->loginKey);
        PluginManager::self()->save(act);
        settings->endGroup();
        ++it;
    }
    return true;
}

void AccountManager::setSettings(QSettings* settings)
{
    this->settings = settings;
    PluginManager::self()->setSettings(settings);
}

int AccountManager::addNewAccount(QString user, QString pwd)
{
    QMap<uint, Account*>::Iterator it = actMap.begin();
    while(it != actMap.end())
    {
        Account* act = *it;
        if(act->user == user)
            return -1;
        ++it;
    }

    Account* act = new Account();
    act->user = user;
    act->pwd = pwd;
    act->uid = 0;
    act->name = user;

    PluginBase* plugin = PluginManager::self()->plugin("Login");
    Task* task = new Task(act, plugin, 0);
    connect(task, SIGNAL(finished(Task*)), this, SLOT(addNewAccountFinished(Task*)));
    TaskManager::self()->appendEmergencyTask(task);
    return 0;
}

void AccountManager::addNewAccountFinished(Task* task)
{
    Account* act = task->act;
    if(!act->login)
    {
        delete task->act;
        return;
    }
    actMap.insert(act->uid, act);
    save();
    load();
    emit updated();
}





